import React, {
    Component
} from "react";
import {
    Platform,
    StyleSheet,
    Text,
    View,
    ScrollView,
    Image,
    Dimensions,
    TouchableOpacity,
    FlatList,
    SafeAreaView,
    NativeModules
} from "react-native";
import moment from 'moment'
import color from "../../widget/color";
import {
    NavigationActions
} from "react-navigation";
import method from '../../api/method'
import api from '../../api/api'
import NetTool from '../../api/NetTool'
import CommonEmptyView from "../../widget/CommonEmptyView";
import CommonCofirmAlertDialog from '../../widget/dialog/CommonCofirmAlertDialog'

import {
    Calendar,
    CalendarList,
    Agenda
} from 'react-native-calendars';
import {
    LocaleConfig
} from 'react-native-calendars';
import Tips from 'react-native-root-tips';
LocaleConfig.locales['fr'] = {
    monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
    dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
    dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
};

LocaleConfig.defaultLocale = 'fr';

type Props = {}
type State = {
    headerUrl: string,
}
const {
    width, height
} = Dimensions.get('window');
/**
 * 日历组件，用于查看相关课程信息
 */
export default class CalendarSecene extends Component < Props, State > {

    static navigationOptions = ({
        navigation
    }: any) => ({
        headerTintColor: 'white',
        headerStyle: {
            backgroundColor: color.globalMainColor
        },
        title: '课程日历',
        headerRight: <Text></Text>,
        transaction: true,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../res/img/video/back.png')}/>
        </TouchableOpacity>
    });

    constructor(props, state) {
        super(props, state)
        this.state = {
            markedDates: {},
            dataAry: [],
            datas: [],
            show:false,
            title:'',
            subtitle:'',
        };
    }


    render() {
        return (
            <SafeAreaView style={{flex:1}}>
                <Calendar
                    monthFormat={'yyyy年MM月'}
                    markedDates={this.state.markedDates}
                    onDayPress={(day)=>{this.getCurrentLesson(day.dateString)}}
                    onMonthChange={(time) => {
                        let year = time.dateString.split("-")[0]
                        let month = time.dateString.split("-")[1]
                        let params = {
                            year:year,
                            month:month,
                        }
                        this.requestData(params)
                    }}
                />
                <Text style={styles.line}/>
                <Text style={styles.titleClass}>课程列表</Text>

                {this.renderList11()}
                <CommonCofirmAlertDialog title={this.state.title} subtitle={this.state.subtitle} closeModal={
                    (st)=>{this.setState({show:st})}
                } show={this.state.show}/>
            </SafeAreaView>
        );
    }
    renderList11(){
        if (this.state.dataAry.length > 0){
            return <FlatList
                data={this.state.dataAry}
                renderItem={(item) => this.renderRow(item)}
                keyExtractor={this.keyExtractor}
            />
        } else {
            return  <CommonEmptyView  height={(height - 300)} tip={'当天暂无课程'} source={require('../../../res/img/select/kecheng.png')}/>
        }
    }


    //刚挂载界面的时候，获取当天日期，请求数据
    componentDidMount() {
        let time = moment(new Date()).format('YYYY-MM-DD')
        let year = time.split("-")[0]
        let month = time.split("-")[1]
        let params = {
            year: year,
            month: month,
        }
        this.requestData(params)

    }
    getCurrentLesson(day) {

        let dataList = this.state.datas
        let datas = []
        dataList.forEach(item => {
            if (item.start_at.substr(0, 10) == day) {
                datas.push(item)
            }
        })

        let time_obj = {}

        this.state.datas.forEach(item => {
            let time = item.start_at.substr(0, 10)
            if (time == day) {
                time_obj[time] = {
                    selected: true
                }
            } else {
                time_obj[time] = {
                    marked: true,
                    dotColor: '#DB3843',
                    activeOpacity: 0,
                }
            }
        })

        console.log(datas)

        this.setState({
            markedDates: time_obj,
            dataAry: datas
        })

        console.log(time_obj, this.state.markedDates)
    }
    requestData = async (params) => {

        let json = await NetTool.fetchGetRequest(api.getUserTable, method.get, params)

        let dataList = json.lessons.map(info => {
            return {
                lesson_id: info.lesson_id,
                lesson: info.lesson,
                start_at: info.start_at,
                course: info.course,
                course_id: info.course_id,
                end_at: info.end_at,
                back_play_url:info.back_play_url,
            }
        })

        let time_obj = {}


        dataList.forEach(item => {
            let time = item.start_at.substr(0, 10)
            time_obj[time] = {
                marked: true,
                dotColor: 'red',
                activeOpacity: 0,
            }
        })


        this.setState({
            datas: dataList,
            markedDates: time_obj
        })


        let time = moment(new Date()).format('YYYY-MM-DD')

        this.getCurrentLesson(time)


    }

    renderRow = (item) => {
        let zhibo_time = new Date(item.item.start_at.replace(/-/g,"/")).getTime()
        let end_time = new Date(item.item.end_at.replace(/-/g,"/")).getTime()

        var stylesdash = styles.dash_black
        let current_time = new Date().getTime()
        var show_btn = ''
        if ((zhibo_time - current_time) > 30 * 60) {
            show_btn = '未开始'
        } else if ((zhibo_time - current_time) < 30 * 60 && (zhibo_time - current_time) > 0) {
            show_btn = '即将开始'
            stylesdash = styles.dash_red
        } else if (current_time > zhibo_time && current_time < end_time) {
            show_btn = '正在直播'
            stylesdash = styles.dash_red
        } else if (current_time > end_time) {
            show_btn = '回放'
        }
        var styles_bg = styles.touch_select_opacity
        var style_txt = styles.touch_select_text
        if (show_btn == '未开始') {
            styles_bg = styles.un_touch_select_opacity
            style_txt = styles.un_touch_select_text
        }

        return (
            <View style={{flexDirection:'row',width: width,backgroundColor:'white'}}>
                    <View style={{width:40,marginBottom:10}}>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <View
                                style={stylesdash}/>
                        </View>
                    </View>
                    <View style={{marginLeft:5,width: width}}>
                        <Text
                            style={{fontSize:12,color:'black',fontWeight:'bold',marginBottom:5,marginTop:5}}>{item.item.start_at.substr(10,6)}</Text>
                        <View style={{flexDirection:'row',justifyContent: 'space-between',marginRight:60}}>
                            <Text
                                style={{fontSize:13,color:'black',fontWeight:'bold',marginBottom:5,marginTop:5}}>{item.item.course.length > 15 ?
                                item.item.course.substr(0, 15) + '...' : item.item.course}</Text>
                            <TouchableOpacity style={styles_bg}
                                              onPress={() =>
                                               this.goToFilm(item)}>
                                <Text style={style_txt}>{show_btn}</Text>
                            </TouchableOpacity>
                        </View>
                        <Text style={{fontSize:13,marginBottom:5,marginTop:5,fontSize:12,color:'rgba(0,0,0,0.5)',fontWeight:'200'}}>{item.item.lesson}</Text>
                    </View>
                </View>
        )



    }


    keyExtractor(item: Object, index: number) {
        return index + ''
    }



    goToFilm(item) {
        let zhibo_time = new Date(item.item.start_at.replace(/-/g,"/")).getTime()
        let end_time = new Date(item.item.end_at.replace(/-/g,"/")).getTime()

        let current_time = new Date().getTime()

         if ((zhibo_time - current_time) < 30 * 60 && (zhibo_time - current_time) > 0) {
             this.setState({show:true, title:'APP暂未开放直播功能', subtitle:'请去www.jkzaixian.com进行观看直播'})

        } else if (current_time > zhibo_time && current_time < end_time) {
             this.setState({show:true, title:'APP暂未开放直播功能', subtitle:'请去www.jkzaixian.com进行观看直播'})

         } else if (current_time > end_time) {

             if (Platform.OS === 'ios') {
                 const navigationAction = NavigationActions.navigate({
                     routeName: 'videoScene',
                     params: {url:item.item.back_play_url,title:item.item.lesson},
                 })
                 this.props.navigation.dispatch(navigationAction)
             } else if (Platform.OS === 'android') {
                 // alert('桥接！')
                 NativeModules.MyVideoModule.callPlayMethod(item.item.back_play_url,item.item.lesson);
             }

        }
    }
}


const styles = StyleSheet.create({
    titleClass: {
        fontSize: 16,
        fontWeight: 'bold',
        paddingLeft: 10,
        paddingTop: 10,
        color: 'black',
        paddingBottom: 10,
        backgroundColor: 'white'
    },

    line: {
        width: width,
        height: 10,
        backgroundColor: '#F9F9F9',
    },
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
    touch_select_opacity: {
        width: 70,
        marginLeft: 3,
        backgroundColor: '#DB3843',
        height: 25,
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
    },
    touch_select_text: {
        color: '#FFFFFF',
        fontSize: 11,
    },
    un_touch_select_opacity: {
        width: 70,
        marginLeft: 3,
        backgroundColor: '#EEEEEE',
        height: 25,
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
    },
    un_touch_select_text: {
        color: '#333333',
        fontSize: 11,
    },
    point: {
        width: 10,
        height: 10,
        borderRadius: 5,
        backgroundColor: '#DB3843',
        left: 20,
        top: 8
    },
    dash_black: {
        marginLeft:20,
        marginTop:10,
        backgroundColor: '#C1C1C1',
        shadowOffset: {
            h: 2,
            w: 2
        },
        shadowRadius: 2,
        shadowOpacity: 0.4,
        width: 5,
        height: 5,
        borderRadius: 2.5,
        borderWidth: 2,
        borderColor: 'rgba(193, 193, 193, 0.3)',
    },
    dash_red: {
        marginLeft:20,
        marginTop:10,
        backgroundColor: 'rgba(219, 56, 67, 1)',
        shadowOffset: {
            h: 2,
            w: 2
        },
        shadowRadius: 2,
        shadowOpacity: 0.4,
        width: 5,
        height: 5,
        borderRadius: 2.5,
        borderWidth: 2,
        borderColor: 'rgba(219, 56, 67, 0.3)',
    },

});